<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Picture extends Controller_DefaultTemplate{

public function action_index()
{
}

public function before()
{
	// Run anything that need ot run before this.
	parent::before();

	if (!Auth::instance()->logged_in())
	{
		$this->request->redirect('/user/login');
	}

}

public function action_list()
{
	$booklet_id = $this->request->param('id');
	if ( $booklet_id )
	{
		$booklet = ORM::factory('booklet')->where('id', '=', $booklet_id)->find();
		if (!$booklet->loaded())
		{
			echo 'booklet_id不存在';
			exit;
		}
		$picture_list = ORM::factory('picture')->where('booklet_id', '=', $booklet_id)->order_by('id', 'DESC')->find_all();
		$this->template->content = View::factory('book/picture_list');
		$this->template->content->set('booklet', $booklet);
		$this->template->content->set('picture_list', $picture_list);
	}
}

public function action_add()
{
	$booklet_id = $this->request->param('id');
	if ( $booklet_id )
	{
		$booklet = ORM::factory('booklet')->where('id', '=', $booklet_id)->find();
		if (!$booklet->loaded())
		{
			echo 'booklet_id不存在';
			exit;
		}
		$this->template->content = View::factory('book/picture_add');
		$this->template->content->set('booklet', $booklet);
	}
}

public function action_save()
{
	$id = $this->request->param('id');
	if ($_POST)
	{
		foreach ($_POST as $key => $value) 
		{
			$picture = ORM::factory('picture');
			$picture->values(array(
				'booklet_id' => $id,
				'description' => arr::get($_POST, 'description'),
				'image' => $value,
			));
			$picture->save();
		}
		$this->request->redirect();
	}
}

public function action_savelist()
{
	$booklet_id = arr::get($_POST, 'booklet_id');
	$frontcover_id = arr::get($_POST, 'frontcover');
	if ($_POST)
	{
		foreach ($_POST as $key => $value)
		{
			$id = $value["id"];
			$description = $value["description"];
			$picture = ORM::factory('picture')->where('id', '=', $id)->find();
			if ($picture->loaded())
			{
				$picture->description = $description;
				$picture->update();
			}
		}

		// 保存封面id
		if ($frontcover_id)
		{
			$booklet = ORM::factory('booklet')->where('id', '=', $booklet_id)->find();
			if ($booklet->loaded())
			{
				$booklet->frontcover = $frontcover_id;
				$booklet->update();
			}
		}
	}

	$this->request->redirect('admin/picture/list/'.$booklet_id);
}

public function action_delete()
{
	$picture_id = $this->request->param('id');
	if ($picture_id)
	{
		$picture = ORM::factory('picture')->where('id', '=', $picture_id)->find();
		if ($picture->loaded())
		{
			$booklet_id = $picture->booklet_id;
			$picture->delete();
			$this->request->redirect();
		}
	}
	
}

}




